#!/usr/bin/env python
import os
import re
import tarfile
import docker
import commands
from utils.log import log

import datetime
import time
from utils.get_date import datelist
from get_date import datelist

def execute(code,account):
    write_data(code,account)
    create_file("test.py", "%soutput.py"%account,account)
    list_date = []
    list_data = []
    list_data_tmp = []
    list_wsvc = []
    list_wsvc_tmp =[]
    a = run_in_docker(account)
    log.info("In execute, the result of run_in_docker:%s" % a)
    str_line = a.split('[')[1]
    str_line = str_line.split(']')[0]
    log.info("In execute: the result of run_in_docker:%s" % str_line)
    list_data_tmp = str_line.split(',')

    #================
    #To get list_date 
    #================
    for i in range(len(list_data_tmp)-1):
        list_data.append(float(list_data_tmp[i]))
    length = len(list_data)
    end = datetime.datetime.now().strftime('%Y/%m/%d')
    log.info("curent date: %s" % end)

    #===================================
    #To get the arguments for datelist()
    #===================================
    this_y = int(end.split("/")[0])
    this_m = int(end.split("/")[1])
    this_d = int(end.split("/")[2])
    start = datetime.datetime.now() + datetime.timedelta(days=-1*length)
    start = start.strftime('%Y/%m/%d')
    start_y = int(start.split("/")[0])
    start_m = int(start.split("/")[1])
    start_d = int(start.split("/")[2])
    #=================
    #To run datelist()
    #=================
    list_date = datelist((start_y, start_m, start_d), (this_y, this_m, this_d))
    log.info("In execute(), list_date: %s" %list_date)
    
    #========================
    #calculating winning rate,
    #max retracement rate,etc
    #========================
    str_wsvc = a.split(")\n")[-1]
    #log.info("str_wsvc: %s" % str_wsvc)
    str_wsvc = str_wsvc.split("\n[")[0]
    list_wsvc_tmp = re.split("\n|:", str_wsvc)
    #log.info("list_wsvc_tmp: %s" % list_wsvc_tmp)
    #log.info(len(list_wsvc_tmp)/2)
    p = 0
    transaction_count = len(list_wsvc_tmp)/2
    for i in range(len(list_wsvc_tmp)/2):
        list_wsvc.append(float(list_wsvc_tmp[2*i+1]))
        if float(list_wsvc_tmp[2*i+1]) >0:
            p = p + 1
    init_capital = list_data[0]
    winning_rate = float(p) / transaction_count
    max_retracement_rate = (init_capital - min(list_data))/init_capital
    total_gain = list_data[-1]-init_capital
    total_gain_rate = (list_data[-1]-init_capital)/(list_data[0]*length)   
    list_info = [init_capital,transaction_count,winning_rate,max_retracement_rate,total_gain,total_gain_rate]

    return list_date, list_data, list_info

def write_data(data,account):
    output_file = open('%soutput.py'%account, 'wb')
    output_file.write(data)
    output_file.close()

def create_input(init_capital,calcgap,account):
    fo = open('%sinput'%account, 'wb')
    fo.write('%s\n'%init_capital)
    fo.write('%s\n'%calcgap)
    fo.close()

def create_file(file1, file2,account):
    file_origin = open(file1, "r")
    content = file_origin.read()
    content_add = ""
    pos = content.find("#insert above")

    #if the code is not written in the file 'file2', then pass.
    if os.path.getsize(file2) == 0:
        content = content[:pos] + "    pass\n" + content[pos:]
    else:
        file_add = open(file2, "r")
        while 1:
            line = file_add.readline()
            if not line:
                break
            new_line = line.rstrip() + '\n'
            content_add = content_add + new_line
        content = content[:pos] + content_add + content[pos:]
        file_add.close()

    file_origin = open(("./%snew_sim.py"%account), "w")
    file_origin.write(content)
    file_origin.close()

def run_in_docker(account):
    tar = tarfile.open("dockertar.tar", "w")
    #tar.add("simulation.py")
    tar.add(("%snew_sim.py"%account))
    tar.add("fetchdata.py")
    tar.add("train_svc.py")
    tar.add("tranpoint.py")
    tar.add("tool.py")
    tar.add("show.py")
    tar.add("data")
    tar.close()
    log.info("tar is created.")
    data = open("dockertar.tar").read()

    status, container_id = commands.getstatusoutput("docker run -d -i -t zwc/ubuntu17.10:beta /bin/bash")
    #log.info("In docker: %s %s" % (status, container_id))
    client = docker.from_env()
    con = client.containers.get(container_id)
    con.put_archive('/root', data)
    ret = con.exec_run("python /root/%snew_sim.py"%account)
    #ret = con.exec_run("python /root/simulation.py")
    log.info("In docker, result: %s" % ret)
    con.kill()

    return ret

#=================
#for rerun testing
#=================
def rerun_in_docker(account):
    tar = tarfile.open("%sdockertar.tar"%account, "w")
    tar.add(("%snew_sim.py"%account))
    tar.add(("%sinput"%account))
    tar.add("fetchdata.py")
    tar.add("train_svc.py")
    tar.add("tranpoint.py")
    tar.add("tool.py")
    tar.add("show.py")
    tar.add("data")
    tar.close()
    log.info("rerun tar is created.")
    data = open("%sdockertar.tar"%account).read()

    status, container_id = commands.getstatusoutput("docker run -d -i -t zwc/ubuntu17.10:beta /bin/bash")
    log.info("rerun In docker: %s %s" % (status, container_id))
    client = docker.from_env()
    con = client.containers.get(container_id)
    con.put_archive('/root', data)
    log.info("to rerun")
    #ret = con.exec_run("python /root/%snew_sim.py < /root/%sinput"%(account,account))
    ret = con.exec_run("python /root/%snew_sim.py"%account)
    log.info("rerun done")
    #ret = con.exec_run("python /root/simulation.py")
    log.info("rerun In docker, result: %s" % ret)
    con.kill()

    return ret

if __name__ == "__main__":
    print run_in_docker("")
	
